package com.hx.core.jsonTemplate;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;

/**
 * 自定义模板引擎——引擎类
 */
public class JsonTemplateEngine implements TemplateEngine {
    TemplateConfig cfg;

    private static final String PREFIX = "$";
    private static final String SUFFIX = "$";

    public JsonTemplateEngine() {
    }

    public JsonTemplateEngine(TemplateConfig cfg) {
        this.init(cfg);
    }

    @Override
    public TemplateEngine init(TemplateConfig config) {
        if (null == config) {
            config = TemplateConfig.DEFAULT;
        }
        this.cfg = config;
        return this;
    }

    @Override
    public Template getTemplate(String resource) {
        if (null == this.cfg) {
            this.init(TemplateConfig.DEFAULT);
        }
        StringBuilder stringBuilder = null;
        String path = this.cfg.getPath() + "\\" + resource;
        switch (this.cfg.getResourceMode()) {
            case CLASSPATH:
                stringBuilder = new StringBuilder(ResourceUtil.readStr(path, this.cfg.getCharset()));
                break;
            case FILE:
                stringBuilder = new StringBuilder(ResourceUtil.readStr(path, this.cfg.getCharset()));
                break;
            case WEB_ROOT:
                throw new RuntimeException("暂不支持的模板加载类型");
            case STRING:
                stringBuilder = new StringBuilder(resource);
                break;
            default:
                throw new RuntimeException("暂不支持的模板加载类型");
        }
        return new CustomTemplate(stringBuilder, PREFIX, SUFFIX);
    }

}
